#include <windows.h>
#include <shellapi.h>
#include <winsock.h>
#include <stdio.h>
#include <iphlpapi.h> 
#include <assert.h>

#define IP 127.0.0.1 // IP do servidor
#define PORT 6900    // Porta de Login

static void print_mac_address(unsigned char md[]);
static char mac_address[20];
int get_mac_address(void);

int main(void)
{
	struct sockaddr_in sdAddr, servAddr;
	LPHOSTENT host_entry;
	WSADATA wsaData;
	int sd;
	
	// Aloca o mac em uma matriz
	get_mac_address();
	
	WSAStartup(MAKEWORD(2,1), &wsaData);
	
	if(!(host_entry = gethostbyname(IP)))
		return -1;
		
	// Cria o socket
	if(!(sd = socket(AF_INET, SOCK_DGRAM, 0)))
		return -1;
	
	sdAddr.sin_family = AF_INET;
	sdAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	sdAddr.sin_port = htons(0);
  
	servAddr.sin_family = AF_INET;
	servAddr.sin_addr = *((LPIN_ADDR)*host_entry->h_addr_list);
	servAddr.sin_port = htons(PORT);
	
	// Envia o Mac
	if(!(sendto(sd, mac_address, strlen(mac_address)+1, 0, (LPSOCKADDR) &servAddr, sizeof(struct sockaddr))))
		return -1;
		
	closesocket(sd);
}

int get_mac_address(void)
{
	IP_ADAPTER_INFO AdapterInfo[16];
	DWORD dwBufLen = sizeof(AdapterInfo);
   
	DWORD dwStatus = GetAdaptersInfo(AdapterInfo,&dwBufLen);
	assert(dwStatus == ERROR_SUCCESS);

	PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
	do {
		print_mac_address(pAdapterInfo->Address);
		pAdapterInfo = pAdapterInfo->Next;
	}
	while(pAdapterInfo);
	return 0;
}

static void print_mac_address(unsigned char md[])
{  
	sprintf(mac_address, "%02X-%02X-%02X-%02X-%02X-%02X", md[0], md[1], md[2], md[3], md[4], md[5]);
}
